package com.ltwc.lttv.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ltwc.lttv.R
import com.ltwc.lttv.api.TypeInfoMessage
import com.ltwc.lttv.models.TypeModel

/**
 * Description：
 * Created on 2024/11/4 09:39
 * Organization:华云
 * author：AHuangSHang
 **/
class LeftAdapter(
    private var list: List<TypeModel>,
    private val onCategoryClick: (Int) -> Unit
) :
    RecyclerView.Adapter<LeftAdapter.ViewHolder>() {
    private var typeInfo: List<TypeInfoMessage>? = null

    fun setTypeInfo(info: List<TypeInfoMessage>) {
        typeInfo = info
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val button: TextView = itemView.findViewById(R.id.name)
    }

    private var highlightedPosition = 0
    var selectedPosition = -1 // 记录当前选中的位置，有焦点的位置

    fun getHighlightedPosition(): Int {
        return highlightedPosition
    }

    fun setHighlightedPosition(position: Int) {
        highlightedPosition = position
        notifyItemRangeChanged(0, list.size)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LeftAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_left, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: LeftAdapter.ViewHolder, position: Int) {
        holder.button.text = getItemName(list[position].type)
        // 设置选中项的高亮状态
        holder.itemView.isSelected = (position == highlightedPosition)
        holder.itemView.setBackgroundResource(if (position == highlightedPosition) R.drawable.choose_bg else R.drawable.un_choose_bg)

        // 设置点击事件
        holder.itemView.setOnClickListener {
            onCategoryClick(position)
            setHighlightedPosition(position)
        }
        holder.itemView.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                onCategoryClick(position)
                if (selectedPosition != position) {
                    selectedPosition = position
                }
            }
        }

        if (position == highlightedPosition) {
            holder.itemView.postDelayed({
                holder.itemView.requestFocus()
            }, 10)
        }
    }

    private fun getItemName(type: String): String? {
        for (item in typeInfo!!) {
            if (item.dictValue == type) {
                return item.dictLabel
            }
        }
        return type
    }

    override fun getItemCount() = list.size
}